﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Ortodoctor.modelo;
using Ortodoctor.gridComponent;
using System.Web.Services;
using Ortodoctor.Funcionario.modelo;

namespace Ortodoctor.Funcionario
{
    public partial class Comparecimento : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USUARIO"] == null)
                Response.Redirect("Login.aspx");

            if (Session["alerta"] != null)
            {
                alerta.Style.Add("display", "block");
                alerta.InnerText = "NENHUM PACIENTE COMPARECEU ONTEM? ";
            }
            else
            {
                alerta.Style.Add("display", "none");
            }

            if (Session["DATA"] == null)
            {
                date.InnerText = DateTime.Now.ToString("dd/MM/yyyy");  
                string data = DateTime.Now.ToString("dd/MM/yyyy");
                Session["DATA"] = data;
            }
            else
            {

                date.InnerText = Convert.ToDateTime(Session["DATA"]).ToString("dd/MM/yyyy");
                Session["DATA"] = Convert.ToDateTime(Session["DATA"]).ToString();
            }

            atualizaGrid();

            modeloCliente modelo = new modeloCliente();
            DataTable dt = modelo.getAll();
            dt.DefaultView.Sort = "[nome] ASC";
            dt = dt.DefaultView.ToTable();
            string options = "";
            foreach (DataRow dr in dt.Rows)
            {
                options += string.Format("<option value='{0}' >{1}</option>", dr["id_cliente"].ToString(), dr["nome"].ToString());
            }
            options = "<select id='selectID' style='width: 100%'>" + options + "</select>";
            string selectClient = "$('#selectID').replaceWith($(\""+options+"\"));";


            modeloProcedimento modeloproc = new modeloProcedimento();
            dt = modeloproc.getAll();
            dt.DefaultView.Sort = "[nome_procedimento] ASC";
            dt = dt.DefaultView.ToTable();
            string procedimento = "";
            foreach (DataRow dr in dt.Rows)
            {
                procedimento += string.Format("<option value='{0}' >{1}</option>", dr["id_procedimento"].ToString(), dr["nome_procedimento"].ToString());
            }
            procedimento = "<select id='procedimento' style='width: 100%'>" + procedimento + "</select>";
            string selectProc = "$('#procedimento').replaceWith($(\"" + procedimento + "\"));";

            scripts.InnerHtml = "<script> "+selectClient + selectProc + "</script>";

            modeloDentista md = new modeloDentista();
            DataTable dtmd = Session["USUARIO_ACESSO"].ToString().Equals("2") ? md.getAll() : md.getAll(Convert.ToInt32(Session["ID_CLINICA"]));

            dentista.Items.Clear();
            
            foreach (DataRow dr in dtmd.Rows)
            {
                //dentista.Items.Add(new ListItem(dr["nome"].ToString(), dr["id_dentista"].ToString()));
                dentista.Items.Add(new ListItem(dr["nome"].ToString(), dr["id_funcionario"].ToString()));
            }
        }

        [WebMethod]
        public static string getDados(string page, string rp, string sortname, string sortorder, string query, string qtype)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_COMPARECIMENTO"]);
            grid.page = Convert.ToInt32(page);
            DataTable dt = grid.dados.Clone();

            if (string.IsNullOrEmpty(query))
            {
                int numeroItensPagina = Convert.ToInt32(rp);
                int numeroPagina = Convert.ToInt32(page);
                int inicio = numeroItensPagina * (numeroPagina - 1);

                for (int i = inicio; i < inicio + numeroItensPagina && i < grid.dados.Rows.Count; ++i)
                {
                    DataRow dr = dt.NewRow();
                    foreach (DataColumn dc in dt.Columns)
                        dr[dc.ColumnName] = grid.dados.Rows[i][dc.ColumnName];

                    dt.Rows.Add(dr);
                }
                if (dt.Rows.Count > 0)
                {
                    dt.DefaultView.Sort = sortname + " " + sortorder;
                    dt = dt.DefaultView.ToTable();
                }
            }
            else
            {
                dt = grid.dados.Copy();
                dt.DefaultView.RowFilter = string.Format("[{0}] like '%{1}%'", qtype, query);
                dt = dt.DefaultView.ToTable();
            }
            return grid.getDadosToJson(dt);
        }

        [WebMethod]
        public static string addToTable(string dados, string hora)
        {
            string[] array = dados.Split('|');

            modeloComparecimento model = new modeloComparecimento();
            if (model.getClientDia(Convert.ToInt32(array[0]), array[2]).Rows.Count == 0)
            {
                model = new modeloComparecimento();
                model.insert(Convert.ToInt32(array[0]), Convert.ToInt32(array[1]), array[2], hora);

                atualizaGrid();
                return "adicionou";
            }
            else
                return "erro";
        }

        private static void atualizaGrid()
        {
            modeloComparecimento model = new modeloComparecimento();
            Grid grid = null;
            if (HttpContext.Current.Session["ID_CLINICA"] == null)
                grid = new Grid(model.getAll(HttpContext.Current.Session["DATA"].ToString()), "id_cliente");
            else
                grid = new Grid(model.getAll(Convert.ToInt32(HttpContext.Current.Session["ID_CLINICA"]), HttpContext.Current.Session["DATA"].ToString()), "id_cliente");

            DataTable dt = new DataTable();
            foreach (DataColumn dc in grid.dados.Columns)
                dt.Columns.Add(dc.ColumnName, typeof(string));

            foreach (DataRow dr in grid.dados.Rows)
            {
                DataRow drow = dt.NewRow();
                foreach (DataColumn dc in grid.dados.Columns)
                {
                    if(dc.ColumnName.ToUpper().Equals("DATA"))
                        drow[dc.ColumnName] = Convert.ToDateTime(dr[dc.ColumnName]).ToString("dd/MM/yyyy");
                    else
                        drow[dc.ColumnName] = dr[dc.ColumnName].ToString();
                }
                dt.Rows.Add(drow);
            }
            grid.dados = dt;

            HttpContext.Current.Session["GRID_COMPARECIMENTO"] = grid;
        }

        [WebMethod]
        public static string deleteFromTable(int id)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_COMPARECIMENTO"]);
            modeloComparecimento COMP = new modeloComparecimento();
            COMP.delete(id, HttpContext.Current.Session["DATA"].ToString());
            atualizaGrid();
            return "removeu";
        }

        [WebMethod]
        public static string getDate(string data, int maioumeno)
        {
            try
            {
                DateTime date = Convert.ToDateTime(data).AddDays(maioumeno);
                HttpContext.Current.Session["DATA"] = date.ToString("dd/MM/yyyy");
                //System.Windows.Forms.MessageBox.Show("retorno da funcal = " + date.ToString("dd/MM/yyyy"));
                atualizaGrid();
                
                return date.ToString("dd/MM/yyyy");
            }
            catch
            {
                return "ERRO";
            }
        }

        [WebMethod]
        public static string getPermissao()
        {
            return HttpContext.Current.Session["USUARIO_ACESSO"].ToString();
        }
    }
}